import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;


public class Dog {
	
	public Thread life = new Thread(){
		public void run(){
			while (true){
				int roll = (int)(Math.random()*4);
				switch(roll){
					case 0: fireDogHungry();break;
					case 1: fireDogLonely();break;
					case 2: fireDogThirsty();break;
					case 3: fireDogSleeps();
				}
				try{
					sleep(5000);}
				catch(Exception e){}
				}
			}
		};
	
	
	private Set<DogListener> listeners;
	private String name;
	
	public Dog(String name){
		this.name = name;
		listeners = new HashSet<DogListener>();
		life.start();
	}
	
	public String getName(){
		return this.name;
	}
    public synchronized void addDogListener( DogListener listener){
    	listeners.add(listener);
    }
    public synchronized void removeDogListener( DogListener listener){
    	listeners.remove(listener);
    }
    
    public synchronized void fireDogHungry(){
    	System.out.println(name + " is hungry!");
    	DogEvent e = new DogEvent(this);
    	
    	for(DogListener listener:listeners){
    		listener.dogHungry(e);
    	}
    }
    
    public synchronized void fireDogThirsty(){
    	System.out.println(name + " is thirsty!");
    	DogEvent e = new DogEvent(this);
    	
    	for(DogListener listener:listeners){
    		listener.dogThirsty(e);
    	}
    }
    public synchronized void fireDogLonely(){
    	System.out.println(name + " is lonely!");
    	DogEvent e = new DogEvent(this);
    	
    	for(DogListener listener:listeners){
    		listener.dogLonely(e);
    	}
    }
    
    public synchronized void fireDogSleeps(){
    	System.out.println(name + " is sleepy!");
    	DogEvent e = new DogEvent(this);
    	
    	for(DogListener listener:listeners){
    		listener.dogSleeps(e);
    	}
    }
}
